package xuebing.api.learning;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Counter {
    private int count = 0;
    private int numThreads;

    public Counter(int numThreads) {
        this.numThreads = numThreads;
    }

    public synchronized void increment() {
        count++;
    }

    public void count() throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        for (int i = 0; i < numThreads; i++) {
            executor.execute(() -> {
                for (int j = 0; j < 1000000; j++) {
                    increment();
                }
            });
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有任务完成
        }
        System.out.println("Count is: " + count);
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter(5);
        counter.count();
    }
}

